package com.wsz.user.controller;

import com.wsz.pojo.Essays;
import com.wsz.pojo.R;
import com.wsz.pojo.dto.EssayDto;
import com.wsz.pojo.query.EssayQuery;
import com.wsz.pojo.vo.EssayVo;
import com.wsz.user.service.EssaysService;
import com.wsz.user.utils.RedisUtils;
import com.wsz.utils.SecurityContextUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
@RestController
public class EssaysController {

    private final EssaysService essaysService;

    private final RedisUtils redisUtils;

    @PostMapping("/release")
    public R release(@RequestBody EssayDto essayDto){
        return essaysService.release(essayDto);
    }


    @PostMapping("/essays/{userId}/{limit}/{page}")
    public R getEaasys(@PathVariable String userId,
                       @PathVariable Long limit,
                       @PathVariable Long page,
                       @RequestBody(required = false) EssayQuery essayQuery){
        return essaysService.getEssays(userId,limit,page,essayQuery);
    }

    @DeleteMapping("/delete/essay")
    public R deleteEssay(@RequestParam("id") String id){
        if(!SecurityContextUtils.getUserUserName().equals(essaysService.getById(id).getAuthor())) return R.error().message("没有权限");
        boolean b = essaysService.removeById(id);
        if(b) return R.ok();
        return R.error().message("删除失败");
    }


    @DeleteMapping("/delete/essay/acl")
    public R deleteEssayAcl(@RequestParam("id") String id,
                            @RequestParam("userId") String userId){
        if(redisUtils.get("acl_essay_delete" + userId) == null) return R.error().message("没有权限");
        boolean b = essaysService.removeById(id);
        if(b) return R.ok();
        return R.error().message("删除失败");
    }


    @GetMapping("/essay")
    public R getEssay(@RequestParam("id") String id){
        Essays essay = essaysService.getById(id);
        EssayVo essayVo = new EssayVo();

        BeanUtils.copyProperties(essay,essayVo);

        return R.ok().data("essay",essayVo);
    }


    @PutMapping("/essay")
    public R updateEassay(@RequestBody EssayDto essayDto){
        if(!SecurityContextUtils.getUserUserName().equals(essaysService.getById(essayDto.getId()).getAuthor())) return R.error().message("没有权限");
        return essaysService.updateEssay(essayDto);
    }

}
